package org.xiaojinlong.net;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class SocketChannelTest {
    public static void main(String[] args) throws Exception {
        //建立到服务端的链接
        SocketAddress address = new InetSocketAddress("127.0.0.1", 9000);
        SocketChannel client = SocketChannel.open(address);
        //创建静态的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(256);

        //将position重新置为0
        buffer.clear();
        //读取数据,到buffer中
        client.read(buffer);
        //输出缓冲区的数据

        byte[] buf = buffer.array();
        for (int i = 0; i < buf.length; i++) {
            System.out.println(buf[i]);
        }

        ByteBuffer writeBuf = ByteBuffer.allocate(256);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.nextLine();
            writeBuf.put(message.getBytes());
            client.write(writeBuf);
        }
    }
}
